﻿using System;
using System.Collections.Generic;
using Ping9719.DeviceCommunication;
using Ping9719.DeviceCommunication.Common.Helpers;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using Ping9719.WpfEx;
using System.Threading;
using System.Windows;

namespace BaseUi.Device
{
    public class ReadCodeBan : Ping9719.DeviceCommunication.SerialPortBase
    {

        static readonly object locklog = new object();
        /// <summary>
        /// 使用串口的方式
        /// </summary>
        public ReadCodeBan(string portName, int baudRate = 9600, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
        {
            if (serialPort == null)
                serialPort = new SerialPort();
            serialPort.PortName = portName;
            serialPort.BaudRate = baudRate;
            serialPort.Parity = parity;
            serialPort.DataBits = dataBits;
            serialPort.StopBits = stopBits;
            //serialPort.Encoding = Encoding.UTF8;
            serialPort.Open();
        }
        public string imei()
        {
            try
            {
                TextBoxLog.AddLog($"串口发送：AT+IMEI?\r\n");
                SendData("AT+IMEI?\r\n");
                //TextBoxLog.AddLog($"串口发送{aaa}");
                var aaa = GetData(500, 2000);
                TextBoxLog.AddLog($"串口接收：{aaa}");
                return aaa;
            }
            catch (Exception ee)
            {
                return "报错"+ee.ToString();

            }
            //var conn = Connect();
            //serialPort.DataReceived += Serialport_receData;
        }
        public string sn()
        {
            try
            {
                TextBoxLog.AddLog($"串口发送：AT+DEVID?\r\n");
                SendData("AT+DEVID?\r\n");
                //TextBoxLog.AddLog($"串口发送{aaa}");
                var aaa = GetData(500, 2000);
                TextBoxLog.AddLog($"串口接收：{aaa}");
                return aaa;
            }
            catch (Exception ee)
            {
                return "报错"+ee.ToString();

            }
            //var conn = Connect();
            //serialPort.DataReceived += Serialport_receData;
        }
        public string icc()
        {
            try
            {
                TextBoxLog.AddLog($"串口发送：AT+ICCID?\r\n");
                SendData("AT+ICCID?\r\n");
                //TextBoxLog.AddLog($"串口发送{aaa}");
                var aaa = GetData(500, 2000);
                TextBoxLog.AddLog($"串口接收：{aaa}");
                return aaa;
            }
            catch (Exception ee)
            {
                return "报错"+ee.ToString();

            }
            //var conn = Connect();
            //serialPort.DataReceived += Serialport_receData;
        }
        public static void SendData(SerialPort port, string data)
        {
            try
            {
                port.DiscardInBuffer();
                port.DiscardOutBuffer();
                port.Write(data);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void Serialport_receData(object sender, SerialDataReceivedEventArgs e)
        {
            
            //if (HomeView.viewModel.Working)
            //{
            //    return;
            //}
            //serialPort.ReadTimeout = 500;
            //serialPort.WriteTimeout = 500;
            //homeViewModel.runstart = 1;
            lock (locklog)
            {
                Thread.Sleep(300);
                var aaa = GetData(serialPort,200, 200);
                TextBoxLog.AddLog(aaa);
                //if (!aaa.IsSucceed)
                //{
                //    TextBoxLog.AddLog("启动暂停通信失败");
                //}
                //if (aaa.Value != null)
                //{
                //    var rest = Encoding.Default.GetString(aaa.Value);
                    
                    
                //        TextBoxLog.AddLog(rest);
                //        return;

                    
                //}
            }
        }
        /// <summary>
        /// 读取返回字符串
        /// </summary>
        /// <param name="port">串口</param>
        /// <param name="timeOut">返回超时ms</param>
        /// <param name="timeWait">返回等待ms</param>
        /// <returns></returns>
        public static string GetData(SerialPort port, int timeOut, int timeWait)
        {
            try
            {
                //返回值buffer
                byte[] buffer = new byte[] { };
                //返回等待
                if (timeWait != 0)
                {
                    Thread.Sleep(timeWait);
                }
                //循环读取
                while (true)
                {
                    //缓存区字节>0 或 超时
                    if (port.BytesToRead > 0 || timeOut <= 0)
                    {
                        byte[] recData = new byte[port.BytesToRead];
                        if (port.BytesToRead > 0)
                        {
                            port.Read(recData, 0, recData.Length);
                            var date = recData.Where(c => c <= 127).ToArray();
                            //存入返回值
                            if (date.Length > 0)
                            {
                                buffer = buffer.Concat(date).ToArray();
                            }
                        }
                        Thread.Sleep(50);
                        timeOut -= 50;
                        //缓存区为空或者超时1S
                        if (port.BytesToRead == 0 || timeOut <= 0)
                            break;
                    }
                    Thread.Sleep(50);
                    timeOut -= 50;
                }
                string reData = "";
                reData += Encoding.Default.GetString(buffer);
                //未读取到数据
                if (reData == "" && timeOut <= 0)
                {
                    return "返回超时";
                }
                return reData;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public bool open()
        {
            var conn = Connect();
            return serialPort.IsOpen;
        }
    }
}
